using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace WebApplication
{
	/// <summary>
	/// Summary description for CompanyBuyPrivateCompany.
	/// </summary>
	public partial class CompanyBuyPrivateCompany : System.Web.UI.Page
	{
		private	bool	_bBuyer;
		private	bool	_bSeller;
		private	string	_sBuyer;
		private	string	_sSeller;

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    

		}
		#endregion

		protected void Page_Load(object sender, System.EventArgs e)
		{
			Game	game		= Global.getGame (this);;
			string	sPlayer		= Session["PlayerName"].ToString ();
			bool	bPriority	= sPlayer == game.PrivateCompanyPriorityPlayerName;
			
			ErrorMsg.Text = "";
			
			SetTitle(sPlayer);
			PriorityCheckBox.Text = sPlayer;

			FillTableWithPlayerInfo();

			PriorityCheckBox.Checked = bPriority;

			if (game.PrivateCompanySalePending)
			{
				Money.Text = game.CurrentlyOperatingCompany.Name + " has $" + game.CurrentlyOperatingCompany.Cash;

				Price.Enabled	= false;
				Accept.Enabled	= false;
                Reject.Enabled  = false;
                Back.Visible    = bPriority;
            }
			else if (game.PrivateCompanySale)
			{
				int		nAmount		= game.PrivateCompanySalePrice;
				string	sCompany	= game.PrivateCompanyForSale.Name;
				bool	bBidEntered	= nAmount > 0;

				_sBuyer		= game.PrivateCompanyBuyingCompany.Name;
				_sSeller	= game.PrivateCompanySeller.Name;
				_bBuyer		= sPlayer == game.CurrentOperatingOwner();
				_bSeller	= sPlayer == _sSeller;

				Money.Text = _sBuyer + " has $" + game.PrivateCompanyBuyingCompany.Cash + ", " + _sSeller + " has $" + game.PrivateCompanySeller.Cash;

				Min.Text	= (game.PrivateCompanyForSale.Cost / 2).ToString();
				Max.Text	= (game.PrivateCompanyForSale.Cost * 2).ToString();
			
				Back.Visible = false;

				if (_bBuyer)			// I am buying
				{
					if (nAmount == 0)	// no bid
						nAmount	= game.PrivateCompanyForSale.Cost;
					else
						nAmount	= game.PrivateCompanySalePrice;
				
					if (!IsPostBack)
						Price.Text	= nAmount.ToString();

					if (!game.PrivateCompanySold)	// offer not accepted
					{
						Status.Text = "Price you wish to pay for the " + sCompany + "?";
				
						Accept.Text = "Buy";
						Reject.Text = "Cancel";
					
						Accept.Enabled	= !bBidEntered;
						Reject.Enabled	= !bBidEntered;
						Price.Enabled	= !bBidEntered;
					}
					else
					{
						if (game.PrivateCompanySalePrice > 0)	// offer accepted ?
							Status.Text = "You bought the " + sCompany + " from " + _sSeller + " for $" + game.PrivateCompanySalePrice;
						else
							Status.Text = "Your offer to buy the " + sCompany + " from " + _sSeller + " was rejected";
				
						Accept.Visible	= false;
						Reject.Text		= "Done";
						Price.Enabled	= false;
					}
				}
				else if (_bSeller)		// I am selling
				{
					Price.Text	= nAmount.ToString();

					if (!game.PrivateCompanySold)	// offer not accepted
					{
						Status.Text = _sBuyer + " wishes to buy the " + sCompany + " from you for $" + nAmount;
			
						Accept.Text = "Accept";
						Reject.Text = "Reject";

						Accept.Enabled = bBidEntered;
						Reject.Enabled = bBidEntered;
					}
					else
					{
						if (game.PrivateCompanySalePrice > 0)	// offer accepted ?
							Status.Text = "You sold the " + sCompany + " to " + _sBuyer + " for $" + nAmount;
						else
							Status.Text = "You rejected the offer to sell the " + sCompany + " to " + _sBuyer;
			
						Accept.Enabled = false;
						Reject.Enabled = false;
					}
				
					Price.Enabled = false;
				}
				else					// I am viewing
				{
					Price.Text	= nAmount.ToString();

					if (!game.PrivateCompanySold)	// offer not accepted
						Status.Text = _sBuyer + " is attempting to buy the " + sCompany + " from " + _sSeller + " for $" + nAmount;
					else if (game.PrivateCompanySalePrice > 0)
						Status.Text = _sBuyer + " bought the " + sCompany + " from " + _sSeller + " for $" + nAmount;
					else
						Status.Text = _sBuyer + "'s offer to buy the " + sCompany + " from " + _sSeller + " was rejected";

					Accept.Visible	= false;
					Reject.Visible	= false;
					Price.Enabled	= false;
				}
			}
			else
			{
				Response.Redirect("OperatingRound2.aspx");
			}
		}

		private void SetTitle (string sNewTitle)
		{
			HtmlGenericControl title = this.FindControl ("Title") as HtmlGenericControl;

			if (title != null)
				title.InnerText = sNewTitle;
		}

		private void FillTableWithPlayerInfo ()
		{
			int 	nRow = 0;
			Game	game = Global.getGame (this);;
			string	sPlayer = Session["PlayerName"].ToString ();

			foreach (Player player in game.Players)
			{
				TableRow	row	;
				TableCell	cell;

				nRow++;
				
				row		= new TableRow();
				cell	= new TableCell();
				
				cell.Text = player.Name;
				row.Cells.Add(cell);
				
				cell	= new TableCell();
				
				// add privates to players line
				foreach (PrivateCompany privateCompany in player.PrivateCompanies)
				{
					Button	button;
					
					button = new Button();
					button.Text = privateCompany.NickName;
					button.Click += new System.EventHandler(this.BuyPrivate);
					button.Enabled = sPlayer == game.CurrentOperatingOwner() && game.PrivateCompanySalePending;
					button.CommandName = player.Name;					// owner
					button.CommandArgument = privateCompany.NickName;	// private
					button.ToolTip = privateCompany.Name + "\n" + "Cost: " + privateCompany.Cost + "\n" + "Income: " + privateCompany.Income;

					cell.Controls.Add(button);
				}

				row.Cells.Add (cell);
				
				PlayerTable.Rows.AddAt(nRow, row);
			}
		}

		private void BuyPrivate(object sender, System.EventArgs e)
		{
			Game	game	= Global.getGame (this);;
			string	sPlayer = Session["PlayerName"].ToString ();
			Button	button	= (Button) sender;

			string			sSeller;
			string			sPrivate;
			Player			seller	= null;
			PrivateCompany	company	= null;

			sSeller = button.CommandName;
			sPrivate = button.CommandArgument;

			seller = game.Players[sSeller];
			company	= seller.PrivateCompanies[sPrivate];

			// redirect to another page between buyer & seller to agree on price for private
			game.PrivateCompanySale = true;
			game.PrivateCompanySeller = seller;
			game.PrivateCompanyForSale = company;
			game.PrivateCompanySalePending = false;
			
			Response.Redirect("CompanyBuyPrivateCompany.aspx");	// redirect buyer to buy screen
		}

		protected void Accept_Click(object sender, System.EventArgs e)
		{
			Game	game	= Global.getGame (this);;
			string	sPlayer = Session["PlayerName"].ToString ();

			if (_bBuyer)
			{
				int	nBid = -1;
				
				bool bBid = int.TryParse(Price.Text, out nBid);
				
				if (!bBid)
				{
				    return;
				}

				if (nBid > 0)
				{
					if (game.CurrentlyOperatingCompany.Cash >= nBid)
					{
						game.PrivateCompanySalePrice = nBid;
						
						if (_bBuyer && !_bSeller)	// buying from another player
						{
							game.PrivateCompanyPriorityPlayerName = _sSeller;
					
							PriorityCheckBox.Checked = false;
						}
						else						// buying from myself
						{
							string	sMsg;

							sMsg = _sBuyer + " bought the " + game.PrivateCompanyForSale.NickName + " from " + _sSeller + " for $" + game.PrivateCompanySalePrice;
								
							game.History.Add (sMsg);

							// transfer the company and money
							PublicCompany	buyer	= game.PrivateCompanyBuyingCompany;
							Player			seller	= game.Players[_sSeller];

							buyer.BuyPrivateCompany(seller, game.PrivateCompanyForSale, game.PrivateCompanySalePrice);

							game.PrivateCompanyPriorityPlayerName = game.CurrentOperatingOwner();
							game.PrivateCompanySold = true;
				
							PriorityCheckBox.Checked = false;

							Response.Redirect("OperatingRound2.aspx");
						}
					}
					else
					{
						ErrorMsg.Text = _sBuyer + " doesn't have enough cash.  It only has $" + game.PrivateCompanyBuyingCompany.Cash.ToString();
					}
				}
			}
			else if (_bSeller)
			{
				string	sMsg;

				sMsg = _sBuyer + " bought the " + game.PrivateCompanyForSale.NickName + " from " + _sSeller + " for $" + game.PrivateCompanySalePrice;
								
				game.History.Add (sMsg);

				// transfer the company and money
				PublicCompany	buyer	= game.PrivateCompanyBuyingCompany;
				Player			seller	= game.Players[_sSeller];

				buyer.BuyPrivateCompany(seller, game.PrivateCompanyForSale, game.PrivateCompanySalePrice);

				game.PrivateCompanyPriorityPlayerName = game.CurrentOperatingOwner();
				game.PrivateCompanySold = true;
				
				PriorityCheckBox.Checked = false;

				Response.Redirect("OperatingRound2.aspx");
			}
		}
		
        protected void Reject_Click(object sender, System.EventArgs e)
		{
			Game	game	= Global.getGame (this);;
			
			if (_bBuyer)
			{
				game.ResetPrivateSaleInfo();
			}
			else if (_bSeller)
			{
				game.PrivateCompanySalePrice = 0;	// tell him rejected
				game.PrivateCompanyPriorityPlayerName = _sBuyer;
				game.PrivateCompanySold = true;
				
				PriorityCheckBox.Checked = false;
			}

			Response.Redirect("OperatingRound2.aspx");
		}

		protected void Back_Click(object sender, System.EventArgs e)
		{
            Game game = Global.getGame(this); ;
            
            PriorityCheckBox.Checked = false;

            // set flags as nothing happened and resume operating round
            game.PrivateCompanySale = false;
            game.PrivateCompanySalePending = false;
            
            Response.Redirect("OperatingRound2.aspx");
		}
	}
}
